// Copyright 2024 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_file_manager_platform_interface/flutter_file_manager_platform_interface.dart';
import 'package:mime/mime.dart';

import 'src/messages.g.dart';

/// The Ohos implementation of [FileManagerPlatform].
///
/// This class implements the `package:flutter_file_manager` functionality for Ohos.
class FlutterFileManagerOhos extends FileManagerPlatform {
  /// Creates a new plugin implementation instance.
  FlutterFileManagerOhos({
    @visibleForTesting FileManagerApi? api,
  }) : _api = api ?? FileManagerApi();

  final FileManagerApi _api;

  /// Registers this class as the default instance of [FileManagerPlatform].
  static void registerWith() {
    FileManagerPlatform.instance = FlutterFileManagerOhos();
  }

  @override
  Future<String> writeFile({
    required String fileName,
    required Uint8List bytes,
  }) async {
    print('[FlutterFileManagerOhos] Starting writeFile operation');
    print('[FlutterFileManagerOhos] fileName: $fileName');
    print('[FlutterFileManagerOhos] bytes length: ${bytes.length}');
    
    // 验证输入参数
    if (fileName.isEmpty) {
      print('[FlutterFileManagerOhos] Error: fileName is empty');
      throw FileSaverException(
        code: 'INVALID_ARGUMENTS',
        message: 'fileName cannot be empty',
        details: null,
      );
    }

    if (bytes.isEmpty) {
      print('[FlutterFileManagerOhos] Error: bytes is empty');
      throw FileSaverException(
        code: 'INVALID_ARGUMENTS',
        message: 'bytes cannot be empty',
        details: null,
      );
    }

    // 验证文件名格式
    if (!_isValidFileName(fileName)) {
      print('[FlutterFileManagerOhos] Error: Invalid file name format');
      throw FileSaverException(
        code: 'INVALID_FILE_NAME',
        message: 'Invalid file name format',
        details: null,
      );
    }

    final mimeType = lookupMimeType(fileName);
    print('[FlutterFileManagerOhos] MIME type: $mimeType');
    
    try {
      print('[FlutterFileManagerOhos] Calling native API writeFile...');
      final path = await _api.writeFile(
        fileName: fileName,
        mimeType: mimeType,
        bytes: bytes,
      );
      print('[FlutterFileManagerOhos] Native API returned path: $path');
      return path;
    } on PlatformException catch (e, s) {
      print('[FlutterFileManagerOhos] PlatformException caught: ${e.code} - ${e.message}');
      print('[FlutterFileManagerOhos] Exception details: ${e.details}');
      switch (e.code) {
        case 'CANCELLED':
          throw FileSaverCancelledException();
        case 'PERMISSION_DENIED':
          throw FileSaverException(
            code: e.code,
            message: 'Permission denied. Please check file access permissions.',
            details: e.details,
            stacktrace: s.toString(),
          );
        case 'INSUFFICIENT_STORAGE':
          throw FileSaverException(
            code: e.code,
            message: 'Insufficient storage space.',
            details: e.details,
            stacktrace: s.toString(),
          );
        case 'INVALID_FILE_NAME':
          throw FileSaverException(
            code: e.code,
            message: 'Invalid file name format.',
            details: e.details,
            stacktrace: s.toString(),
          );
        case 'INVALID_ARGUMENTS':
          throw FileSaverException(
            code: e.code,
            message: 'Invalid arguments provided.',
            details: e.details,
            stacktrace: s.toString(),
          );
        case 'NETWORK_ERROR':
          throw FileSaverException(
            code: e.code,
            message: 'Network error occurred.',
            details: e.details,
            stacktrace: s.toString(),
          );
        case 'TIMEOUT':
          throw FileSaverException(
            code: e.code,
            message: 'Operation timed out.',
            details: e.details,
            stacktrace: s.toString(),
          );
        case 'UNEXPECTED_ERROR':
          throw FileSaverException(
            code: e.code,
            message: 'An unexpected error occurred.',
            details: e.details,
            stacktrace: s.toString(),
          );
        default:
          throw FileSaverException(
            code: e.code,
            message: e.message,
            details: e.details,
            stacktrace: s.toString(),
          );
      }
    } catch (e, s) {
      print('[FlutterFileManagerOhos] Unknown error caught: $e');
      print('[FlutterFileManagerOhos] Stack trace: $s');
      throw FileSaverException(
        code: 'UNKNOWN_ERROR',
        message: 'An unknown error occurred: $e',
        details: null,
        stacktrace: s.toString(),
      );
    }
  }

  /// 验证文件名格式
  bool _isValidFileName(String fileName) {
    // 检查文件名是否包含非法字符
    final invalidChars = RegExp(r'[<>:"/\\|?*]');
    if (invalidChars.hasMatch(fileName)) {
      return false;
    }
    
    // 检查文件名长度
    if (fileName.length > 255) {
      return false;
    }
    
    // 检查是否为空或只包含空格
    if (fileName.trim().isEmpty) {
      return false;
    }
    
    // 检查是否以点开头（隐藏文件）
    if (fileName.startsWith('.')) {
      return false;
    }
    
    return true;
  }
}
